<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-divider content-position="center">个人信息</el-divider>
      <!-- 头像 -->
      <el-form-item label="头像" prop="avatar">
        <UploadImg v-model="formData.avatar" :limit="1" :is-show-tip="false" />
      </el-form-item>

      <!-- 个人信息 -->
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" clearable />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="分销员" prop="groupId">
            <MemberGroupSelect v-model="formData.groupId" />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="formData.birthday"
              type="date"
              value-format="x"
              placeholder="选择出生日期"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="年龄" prop="age"> {{ formData.age || '-' }} 岁 </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="身高" prop="height">
            <el-input
              v-model.number="formData.height"
              v-onlyNumber
              placeholder="请输入身高"
              clearable
            >
              <template #append>cm</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="体重" prop="weight">
            <el-input v-model="formData.weight" v-onlyNumber placeholder="请输入体重" clearable>
              <template #append>kg</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="手机号" prop="mobile">
            <el-input disabled v-model="formData.mobile" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="学历" prop="education">
            <el-select v-model="formData.education" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.USER_EDUCATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="婚况" prop="marriage">
            <el-select
              v-model="formData.marriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MARITAL_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="月收入" prop="monthIncome">
            <el-input
              v-model="formData.monthIncome"
              v-onlyNumber
              placeholder="请输入月收入"
              clearable
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="职业" prop="career">
            <el-cascader
              v-model="formData.career"
              :options="useCareerStore"
              :props="blindCareerProps"
              :show-all-levels="false"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="购房情况" prop="purchasHouse">
            <el-select
              v-model="formData.purchasCar"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PURCHASE_SITUATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="购车情况" prop="purchasCar">
            <el-select
              v-model="formData.purchasCar"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.PURCHASE_CAR)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="有无孩子" prop="withChild">
            <el-select v-model="formData.withChild" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_CHILDREN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否要孩子" prop="wantChild">
            <el-select v-model="formData.wantChild" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.WANT_CHILD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="结婚时间" prop="marryDate">
            <el-date-picker
              v-model="formData.marryDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请输入结婚时间"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否吸烟" prop="smoker">
            <el-select v-model="formData.smoker" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVA_SMOK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否喝酒" prop="drink">
            <el-select v-model="formData.drink" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_DRINK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="民族" prop="nation">
            <el-select v-model="formData.nation" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.NATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="星座" prop="constellation">
            <el-select
              v-model="formData.constellation"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CONSTELLATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="12">
          <el-form-item label="籍贯" prop="weight">
            <el-cascader
              v-model="formData.nativePlace"
              :options="areaList"
              :props="blindAddressProps"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="所在地" prop="areaId" class="areaId">
            <el-cascader v-model="formData.areaId" :options="areaList" :props="blindAddressProps" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="内心独白" prop="innerMonologue">
        <el-input
          v-model="formData.innerMonologue"
          type="textarea"
          maxlength="200"
          show-word-limit
          placeholder="请输入内心独白"
        />
      </el-form-item>

      <el-divider content-position="center">择偶条件</el-divider>

      <!-- 择偶条件 -->
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="年龄" prop="matchAge">
            <el-select v-model="formData.matchAge" placeholder="请选择" clearable class="!w-240px">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MATCHAGE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="身高" prop="matchHeight">
            <el-select
              v-model="formData.matchHeight"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MATCHHEIGHT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="学历" prop="matchEducation">
            <el-select
              v-model="formData.matchEducation"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.USER_EDUCATION)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="婚况" prop="matchMarriage">
            <el-select
              v-model="formData.matchMarriage"
              placeholder="请选择婚况"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MARITAL_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="月收入" prop="matchIncome">
            <el-select
              v-model="formData.matchIncome"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MATCHINCOME)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="有无孩子" prop="matchWithChild">
            <el-select
              v-model="formData.matchWithChild"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_CHILDREN)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否要孩子" prop="matchWantChild">
            <el-select
              v-model="formData.matchWantChild"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.WANT_CHILD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否吸烟" prop="matchSmoker">
            <el-select
              v-model="formData.matchSmoker"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVA_SMOK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="是否喝酒" prop="matchDrink">
            <el-select
              v-model="formData.matchDrink"
              placeholder="请选择"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.HAVE_DRINK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="16" :lg="12" :xl="12">
          <el-form-item label="所在地" prop="matchWorkArea" class="areaId" :checkStrictly="true">
            <el-cascader
              v-model="formData.matchWorkArea"
              :options="areaList"
              :props="blindAddressProps"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { useCareerStoreWithOut } from '@/store/modules/career'
import * as UserApi from '@/api/member/user'
import * as AreaApi from '@/api/system/area'
import { blindAddressProps, blindCareerProps } from '@/utils/tree'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const useCareerStore = useCareerStoreWithOut().getCareer // 职业

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  mobile: undefined,
  password: undefined,
  status: undefined,
  nickname: undefined,
  avatar: undefined,
  name: undefined,
  sex: undefined,
  areaId: 0,
  birthday: undefined,
  mark: undefined,
  tagIds: [],
  groupId: undefined,
  pageNo: 1,
  pageSize: 10,
  loginDate: [],
  createTime: [],
  levelId: null,
  userLevel: null,
  age: null,
  hunKuang: null,
  chindren: null,
  car: null,
  house: null,
  educationAttainment: null,
  smoking: null,
  drink: null,
  timeOfMarriage: null,
  marriage: '',
  withChild: null,
  wantChild: null,
  height: null,
  weight: null,
  education: null,
  smoker: null,
  marryDate: null,
  nation: null,
  monthIncome: null,
  constellation: null,
  nativePlace: 0,
  purchasHouse: null,
  career: null,
  purchasCar: null,
  innerMonologue: null,
  matchAge: null,
  matchHeight: null,
  matchIncome: null,
  matchEducation: null,
  matchMarriage: null,
  matchWorkArea: [],
  matchWithChild: null,
  matchWantChild: null,
  matchSmoker: null,
  matchDrink: null
})
const formRules = reactive({
  nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  birthday: [{ required: true, message: '生日不能为空', trigger: 'blur' }],
  marriage: [{ required: true, message: '婚况不能为空', trigger: 'blur' }],
  height: [{ type: 'text', message: 'age must be a number', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const areaList = ref([]) // 地区列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await UserApi.getUser(id)

      data.nativePlace = Number(data.nativePlace)
      data.areaId = Number(data.areaId)
      data.matchWorkArea = Number(data.matchWorkArea)

      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.UserVO

    if (formType.value === 'create') {
      // 说明：目前暂时没有新增操作。如果自己业务需要，可以进行扩展
      // await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mobile: undefined,
    password: undefined,
    status: undefined,
    nickname: undefined,
    avatar: undefined,
    name: undefined,
    sex: undefined,
    areaId: 0,
    birthday: undefined,
    mark: undefined,
    tagIds: [],
    groupId: undefined,
    pageNo: 1,
    pageSize: 10,
    loginDate: [],
    createTime: [],
    levelId: null,
    userLevel: null,
    age: null,
    hunKuang: null,
    chindren: null,
    car: null,
    house: null,
    educationAttainment: null,
    smoking: null,
    drink: null,
    timeOfMarriage: null,
    marriage: '',
    withChild: null,
    wantChild: null,
    height: null,
    weight: null,
    education: null,
    smoker: null,
    marryDate: null,
    nation: null,
    monthIncome: null,
    constellation: null,
    nativePlace: null,
    purchasHouse: null,
    career: null,
    purchasCar: null,
    innerMonologue: null,
    matchAge: null,
    matchHeight: null,
    matchIncome: null,
    matchEducation: null,
    matchMarriage: null,
    matchWorkArea: [],
    matchWithChild: null,
    matchWantChild: null,
    matchSmoker: null,
    matchDrink: null
  }
  formRef.value?.resetFields()
}

const normalizer = (node) => {
  if (node.children && !node.children.length) {
    delete node.children
  }
  return {
    id: node.code,
    label: node.name,
    children: node.children
  }
}
</script>

<style scoped lang="scss">
.areaId .el-select {
  width: 100%;
}
</style>
